package top.birdhk.TestAPI.sink;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import top.birdhk.TestAPI.beans.SensorReading;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;


/**
 * 向Jdbc中写入数据
 */
public class SinkTest_Jdbc {

    public static void main(String[] args) throws Exception {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> stringDataStreamSource = env.readTextFile("E:\\flink\\wordcount\\src\\main\\resources\\sensor.txt");

        SingleOutputStreamOperator<SensorReading> dataStream = stringDataStreamSource.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], new Long(split[1]), new Double(split[2]));
        });



        dataStream.addSink(new MyJdbcSink());

        env.execute();



    }


    public static class MyJdbcSink extends RichSinkFunction<SensorReading> {

        Connection connection = null;

        PreparedStatement insert = null;

        PreparedStatement update = null;

        @Override
        public void open(Configuration parameters) throws Exception {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","root");
            insert = connection.prepareStatement("insert into sensor_temp (sid,temp) values (?,?)");
            update = connection.prepareStatement("update sensor_temp set temp = ? where sid = ?");
        }

        @Override
        public void close() throws Exception {
            insert.close();
            update.close();
            connection.close();
        }

        // 每来一条数据，调用连接，执行sql
        @Override
        public void invoke(SensorReading value, Context context) throws Exception {
            // 直接执行更新语句，如果没有更新成功就执行插入语句
            update.setDouble(1,value.getTemperature());
            update.setString(2,value.getId());
            update.execute();
            if (update.getUpdateCount() == 0){
                insert.setString(1,value.getId());
                insert.setDouble(2,value.getTemperature());
                insert.execute();
            }
        }
    }


}
